package com.ruihu.admin.common.mybatis;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedTypes(value = List.class)
@MappedJdbcTypes(value = JdbcType.VARCHAR)
public class FastJsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private Class<T> type;

    public FastJsonTypeHandler(Class<T> type) {
        if (null == type)
            throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, T t, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, parseJsonString(t));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return parseJavaObject(resultSet.getString(s));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return parseJavaObject(resultSet.getString(i));
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return parseJavaObject(callableStatement.getString(i));
    }

    private String parseJsonString(T t) {
        if (null == t)
            return null;
        return JSON.toJSONString(t);
    }

    private T parseJavaObject(String string) {
        if (null == string)
            return null;
        if (string.startsWith("[")) {
            return (T)JSON.parseArray(string, this.type);
        }
        return JSON.parseObject(string, this.type);
    }
}
